//
//  T3FMAPolygon.swift
//  t3_map
//
//  Created by Cunhai Li on 2024/10/22.
//

import AMapNaviKit
import UIKit

class T3FMAPolygon: NSObject {

    typealias Value = (fillColor: UIColor?, strokeColor: UIColor?)

    private(set) var options: T3FPolygonOptions
    /// SDK内置的MAPolygon
    let realPolygon: MAPolygon

    /// 重置颜色
    var resetColor: ((Value) -> Void)?

    init(options: T3FPolygonOptions, realPolygon: MAPolygon) {
        self.options = options
        self.realPolygon = realPolygon
    }
}

extension T3FMAPolygon: T3FPolygon {
    func update(points: [CLLocationCoordinate2D]) {
        var coords = points
        let result = realPolygon.setPolygonWithCoordinates(&coords, count: coords.count)
        guard result else {
            return
        }
        options.points = points
    }

    /// 设置 fillColor
    /// - Parameter fillColor: UIColor
    func setup(fillColor: UIColor) {
        options.fillColor = fillColor
        resetColor?((fillColor, nil))
    }

    /// 设置 strokeColor
    /// - Parameter strokeColor: UIColor
    func setup(strokeColor: UIColor) {
        options.strokeColor = strokeColor
        resetColor?((nil, strokeColor))
    }

    func container(coordinate: CLLocationCoordinate2D) -> Bool {

        guard coordinate.latitude > 0, coordinate.longitude > 0 else {
            return false
        }
        return MAPolygonContainsPoint(MAMapPointForCoordinate(coordinate), realPolygon.points, realPolygon.pointCount)
    }
}
